import numpy as np
import cv2,math
from sklearn.cluster import KMeans
from collections import defaultdict

# 红色范围1 (0-10)
lower_red1 = np.array([0, 40, 40])
upper_red1 = np.array([10, 255, 255])

# 红色范围2 (170-180)
lower_red2 = np.array([170, 40, 40])
upper_red2 = np.array([180, 255, 255])

# 定义绿色的HSV范围, 
lower_green = np.array([35, 40, 40])
upper_green = np.array([85, 255, 255])

# 蓝色范围
lower_blue = np.array([100, 40, 40])
upper_blue = np.array([140, 255, 255])


def get_center(img,color,return_image=False):
    img=img.copy()
    center_x=0
    center_y=0
     # 转换到HSV色彩空间
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    if color == 2:
        mask = cv2.inRange(hsv, lower_green, upper_green)
    elif color == 3:
        mask = cv2.inRange(hsv, lower_blue, upper_blue)
    else:
        mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
        mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
        mask = cv2.bitwise_or(mask1, mask2)
      
    # 获取所有像素的坐标
    pixels = np.column_stack(np.where(mask > 0))
    
    if len(pixels) > 0:
        # 计算质心（圆心）
        center_y = int(np.mean(pixels[:, 0]))
        center_x = int(np.mean(pixels[:, 1]))
        if return_image:
            # 计算到中心点最远的距离作为半径
            distances = np.sqrt(np.sum((pixels - [center_y, center_x])**2, axis=1))
            radius = int(np.max(distances))
            
            # 绘制圆心和圆
            cv2.circle(img, (center_x, center_y), 3, (0, 0, 255), -1)  # 红色圆心
            cv2.circle(img, (center_x, center_y), radius, (0, 255, 0), 2)  # 绿色圆轮廓
            # img=mask
        else:
            img=None 
    
    return (center_x,center_y),img

def get_color(img,ran):

    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # 创建颜色掩膜
    mask_red1 = cv2.inRange(hsv, lower_red1, upper_red1)
    mask_red2 = cv2.inRange(hsv, lower_red2, upper_red2)
    mask_red = cv2.bitwise_or(mask_red1, mask_red2)
    
    mask_green = cv2.inRange(hsv, lower_green, upper_green)
    mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
 
    # 计算各颜色区域面积
    red_area = cv2.countNonZero(mask_red)
    green_area = cv2.countNonZero(mask_green)
    blue_area = cv2.countNonZero(mask_blue)
    # print(f"red_area:{red_area},green_area:{green_area},blue_area:{blue_area}")
    # 返回面积最大的颜色（可根据需求调整）
    max_area = max(red_area, green_area, blue_area)
    if max_area <= ran:
        return None  # 没有检测到颜色
    elif red_area == max_area:
        return 1
    elif green_area == max_area:
        return 2
    else:
        return 3


def get_longest_line_angle(img):
    """
    检测图像中最长的直线与X轴的夹角
    
    参数:
        img: OpenCV图像对象 (BGR格式)
        
    返回:
        float: 最长直线与X轴的夹角(度)，范围[-90, 90]
               如果没有检测到直线，返回0度
    """
    # 转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # 边缘检测 (Canny)
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    
    # 使用霍夫变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, 
                           minLineLength=100, maxLineGap=10)
    
    if lines is None:
        return 0.0
    
    # 找出最长的直线
    longest_line = None
    max_length = 0
    
    for line in lines:
        x1, y1, x2, y2 = line[0]
        length = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
        if length > max_length:
            max_length = length
            longest_line = line[0]
    
    if longest_line is None:
        return 0.0
    
    # 计算角度 (与X轴的夹角，范围在-90到90度之间)
    x1, y1, x2, y2 = longest_line
    angle = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
    
    return angle